package com.zlzxm.sorting.ui.view.sortview2

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.zlzxm.sorting.R

/**
 *
 *CREATE BY zlzxm ON 2022/8/22
 **/
class SortView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : RelativeLayout(context,attrs,defStyleAttr),ISortView, OnItemClickListener {

    private val rvIndex:RecyclerView
    private val viewPageProduct:ViewPager2
    private val adapterIndex = AdapterIndex()

    init {

        LayoutInflater.from(context).inflate(R.layout.layout_sorting_view2,this,true)
        rvIndex = findViewById(R.id.rvIndex)
        viewPageProduct = findViewById(R.id.viewPageProduct)
        viewPageProduct.orientation = ViewPager2.ORIENTATION_VERTICAL
        rvIndex.layoutManager = LinearLayoutManager(context)
        rvIndex.adapter = adapterIndex
        adapterIndex.setOnItemClickListener(this)
        viewPageProduct.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)

                adapterIndex.selectPosition(position)
            }
        })

        viewPageProduct.isUserInputEnabled = false

    }

    override fun setNewIndex(index: MutableList<EntityIndex>, fragmentManager:FragmentManager,
                             lifecycle: Lifecycle) {
        adapterIndex.setNewInstance(index)

        viewPageProduct.adapter = object : FragmentStateAdapter(fragmentManager,lifecycle){
            override fun getItemCount(): Int {

                return index.size
            }

            override fun createFragment(position: Int): Fragment {

                return  index[position].page
            }

        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

        viewPageProduct.currentItem = position
    }




}